<template>
  <div class="layout-padding">
    <splitpanes>
      <pane size="15">
        <div class="layout-padding-auto layout-padding-view">
          <el-scrollbar>
            <query-tree :placeholder="$t('common.queryDeptTip')" :query="deptData.queryList" :show-expand="true"
              @node-click="handleNodeClick" :handleKeyChange="keyChangeList">
              <!-- 没有数据权限提示 -->
              <template #default="{ node, data }">
                <el-tooltip v-if="data.isLock" class="item" effect="dark" :content="$t('sysuser.noDataScopeTip')"
                  placement="right-start">
                  <span>{{ node.label }}
                    <SvgIcon name="ele-Lock" />
                  </span>
                </el-tooltip>
                <span v-if="!data.isLock">{{ node.label }}</span>
              </template>
            </query-tree>
          </el-scrollbar>
        </div>
      </pane>

      <pane class="ml8">
        <div class="layout-padding-auto layout-padding-view">
          <el-row>
            <div class="mb8" style="width: 100%">
              <el-row v-show="showSearch">
                <el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList">
                  <el-form-item label="工号" prop="username">
                    <el-input v-model="state.queryForm.username" placeholder="请输入工号" clearable />
                  </el-form-item>
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="state.queryForm.name" placeholder="请输入姓名" clearable />
                  </el-form-item>
                  <el-form-item label="开始时间" prop="name">
                    <el-date-picker arrow-control format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                      v-model="state.queryForm.workStartTime" @change="timeChange1"
                      placeholder="请选择开始时间"></el-date-picker>
                  </el-form-item>
                  <el-form-item label="结束时间" prop="name">
                    <el-date-picker arrow-control format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                      v-model="state.queryForm.workEndTime" @change="timeChange2"
                      placeholder="请选择结束时间"></el-date-picker>
                  </el-form-item>
                  <el-form-item>
                    <el-button icon="Search" type="primary" @click="getDataList">{{ $t('common.queryBtn') }}</el-button>
                    <el-button icon="Refresh" @click="resetQuery">{{ $t('common.resetBtn') }}</el-button>
                    <el-button icon="Refresh" @click="resetNewQuery">重新计算</el-button>
                    <el-button icon="Download" @click="dailyexport">导出</el-button>
                    <!-- <el-button icon="folder-add" type="primary" class="ml10" @click="selectionMoreChangDialog(userList)"
                      v-auth="'personnel_userClasses_add'">
                      批量排班
                    </el-button> -->
                  </el-form-item>
                </el-form>
              </el-row>
            </div>
          </el-row>

          <el-table :data="state.dataList" v-loading="state.loading" border :cell-style="tableStyle.cellStyle"
            :header-cell-style="tableStyle.headerCellStyle" @selection-change="selectionChangHandle"
            @sort-change="sortChangeHandle">
            <!-- <el-table-column type="selection" width="40" align="center" /> -->
            <el-table-column type="index" label="序号" width="60" fixed />
            <el-table-column prop="username" label="工号" fixed />
            <el-table-column prop="name" label="姓名" fixed />
            <el-table-column prop="def1" label="一级部门" show-overflow-tooltip fixed />
            <el-table-column prop="def2" label="二级部门" show-overflow-tooltip fixed />
            <el-table-column prop="def3" label="三级部门" show-overflow-tooltip fixed />
            <el-table-column prop="def4" label="四级部门" show-overflow-tooltip fixed />
            <el-table-column prop="def5" label="五级部门" show-overflow-tooltip fixed />

            <el-table-column prop="date" label="日期" width="120" fixed />
            <el-table-column prop="id" label="身份证" show-overflow-tooltip fixed />
            <el-table-column prop="classesName" label="班次" show-overflow-tooltip fixed />
            <el-table-column prop="groupName" label="班组" show-overflow-tooltip fixed />
            <el-table-column prop="ruleName" label="规则" show-overflow-tooltip fixed />



            <el-table-column prop="shouldAttendanceClasses" label="应出勤班数" />
            <el-table-column prop="attendanceClass" label="出勤班数" />
            <el-table-column prop="attendanceDays" label="出勤天数" />
            <el-table-column prop="numberOfLatencies" label="迟到次数" />
            <el-table-column prop="numberOfEarlyDepartures" label="早退次数" />
            <el-table-column prop="numberOfAbsenteeismClasses" label="旷工次数" />
            <el-table-column prop="numberOfShifts" label="值班个数" />
            <el-table-column prop="thingVacationDays" label="事假(天)" />
            <el-table-column prop="sickenVacationDays" label="病假(天)" />
            <el-table-column prop="marryVacationDays" label="婚假(天)" />
            <el-table-column prop="maternityVacationDays" label="产假(天)" />
            <el-table-column prop="familyVacationDays" label="探亲假(天)" />
            <el-table-column prop="funeralVacationDays" label="丧假(天)" />
            <el-table-column prop="worryThingVacationDays" label="急事请假(天)" />
            <el-table-column prop="a" label="停产放假(天)" />
            <el-table-column prop="a" label="15天以下工伤假(天)" />
            <el-table-column prop="a" label="加班转调休(天)" />


            <el-table-column prop="timeOfLatencies" label="迟到时长" />
            <el-table-column prop="timeOfAbsenteeism" label="旷工时长" />
            <el-table-column prop="shouldAttendanceTime" label="应出勤工时" />
            <el-table-column prop="attendanceTime" label="出勤工时" />
            <el-table-column prop="timeOfEarlyDepartures" label="早退时长" />
            <el-table-column prop="isSunday" label="周日" />
            <el-table-column prop="remark" label="备注" width="170" />


            <!-- <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button icon="edit-pen" text type="primary" v-auth="'personnel_workScheduling_edit'"
                  @click="formDialogRef.openDialog(scope.row.id)">编辑</el-button>
                <el-button icon="delete" text type="primary" v-auth="'personnel_workScheduling_del'"
                  @click="handleDelete([scope.row.id])">删除</el-button>
              </template>
            </el-table-column> -->
          </el-table>
          <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
        </div>
      </pane>
    </splitpanes>


    <!-- 编辑、新增  -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />

  </div>
</template>

<script setup lang="ts" name="systemWorkScheduling">

import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs, tongbu } from "/@/api/personnel/workScheduling";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { deptTree } from "/@/api/personnel/userClasses";
import { formatDate } from '/@/utils/formatTime';
import { useDict } from '/@/hooks/dict';
// 引入组件

const QueryTree = defineAsyncComponent(() => import('/@/components/QueryTree/indexUser.vue'));
// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
// 定义查询字典

// 定义变量内容
const formDialogRef = ref()
// 搜索变量
const queryRef = ref()
const showSearch = ref(true)
//部门list
const keyChangeList = ref([])
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
// 部门树使用的数据
const deptData = reactive({
  queryList: (name: String) => {
    return deptTree({
      deptName: name,
    });
  },
});
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: fetchList
})
state.queryForm.workStartTime = formatDate(new Date(), 'YYYY-mm-dd').substring(0, 8) + '01' + ' 00:00:00'
state.queryForm.workEndTime = formatDate(new Date(), 'YYYY-mm-dd') + ' 23:59:59'
//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state)
// 点击树
const handleNodeClick = (e: any) => {

  state.queryForm.pkDept = e.id;
  getDataList()
};
// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields()
  // 清空多选
  selectObjs.value = []
  getDataList()
}
//重新计算
const resetNewQuery = () => {
  getDataList()
  const date1 = new Date(state.queryForm.workStartTime);
  const date2 = new Date(state.queryForm.workEndTime);
  const timestamp1 = date1.getTime(); // 返回时间戳，单位为毫秒
  const timestamp2 = date2.getTime(); // 返回时间戳，单位为毫秒
  const time = timestamp2 - timestamp1
  // console.log('timestamp1-', timestamp1)
  // console.log('timestamp2-', timestamp2)
  // console.log('计算', timestamp2 - timestamp1)
  if (time > 86400000 * 3) {
    useMessage().error('时间不能超过2天');
    return
  }
  tongbu(state.queryForm).then((res) => {

  })
  // if(time1)

}

const dailyexport = () => {
  downBlobFile('/personnel/workScheduling/dailyexport', Object.assign(state.queryForm), 'workScheduling.xlsx')

}
const timeChange1 = () => {

  state.queryForm.workStartTime += ' 00:00:00'

}
const timeChange2 = () => {

  state.queryForm.workEndTime += ' 23:59:59'

}
// 导出excel
const exportExcel = () => {
  downBlobFile('/personnel/workScheduling/export', Object.assign(state.queryForm, { ids: selectObjs }), 'workScheduling.xlsx')
}

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ id }) => id);
  multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};
</script>